package com.itheima.common;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.itheima.pojo.AliOSSProperties;
import com.itheima.pojo.R;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@Component
@RestController
@RequestMapping("/common")
public class CommonController {
//    @Value("${reggie.path}")
//    private String basePath;

    @Autowired
    private AliOSSProperties aliOSSProperties;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {

//        log.info("上传图片:{}", multipartFile.toString());
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        // 获取上传文件的输入流
        InputStream inputStream = file.getInputStream();

        OSS ossClient = new OSSClientBuilder().build(aliOSSProperties.getEndpoint(), aliOSSProperties.getAccessKeyId(), aliOSSProperties.getAccessKeySecret());
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliOSSProperties.getBucketName(), "image/" + fileName, inputStream);
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        // ossClient.putObject(aliOSSProperties.getBucketName(), "image/" + fileName, inputStream);
        //String url = aliOSSProperties.getEndpoint().split("//")[0] + "//" + aliOSSProperties.getBucketName() + "." + aliOSSProperties.getEndpoint().split("//")[1] + "/image/" + fileName;
        ossClient.shutdown();

//        URL url = new URL(path);
//        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
//        httpUrl.connect();
//        OutputStream outputStream = httpUrl.getOutputStream();
//        File dir = new File(basePath);
//
//        if (!dir.exists()) {
//            dir.mkdir();
//        }
//        int len = 0;
//        byte[] bytes = new byte[1024];
//        while ((len = inputStream.read(bytes)) != -1) {
//            outputStream.write(bytes, 0, len);
//            outputStream.flush();
//        }

//        try {
//            file.transferTo(new File(path));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

//        ossClient.shutdown();

        return R.success(fileName);

    }

    @GetMapping("/download")
    public void download(String name) throws IOException {

        //      String path = aliOSSProperties.getEndpoint().split("//")[0] + "//" + aliOSSProperties.getBucketName() + "." + aliOSSProperties.getEndpoint().split("//")[1] + "/image/" + name;


        OSS ossClient = new OSSClientBuilder().build(aliOSSProperties.getEndpoint(), aliOSSProperties.getAccessKeyId(), aliOSSProperties.getAccessKeySecret());

        OSSObject ossObject = ossClient.getObject(aliOSSProperties.getBucketName(), "image/" + name);
        BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
        while (true) {
            String line = reader.readLine();
            if (line == null) break;
            System.out.println("\n" + line);
        }
        reader.close();
        ossObject.close();

        ossClient.shutdown();


        //String url = aliOSSProperties.getEndpoint().split("//")[0] + "//" + aliOSSProperties.getBucketName() + "." + aliOSSProperties.getEndpoint().split("//")[1] + "/image/" + name;

//            BufferedInputStream bufferedInputStream = new BufferedInputStream(ossObject.getObjectContent());
//        try {
//            URL url = new URL(path);
//            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
//            httpUrl.connect();
//            InputStream inputStream = httpUrl.getInputStream();
//            ServletOutputStream outputStream = response.getOutputStream();
//            response.setContentType("image/jpeg");
//            int len = 0;
//            byte[] bytes = new byte[1024];
//            while ((len = inputStream.read(bytes)) != -1) {
//                outputStream.write(bytes, 0, len);
//                outputStream.flush();
//            }
//            outputStream.close();
//            inputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }


    }
}
//        try {
//
//            FileInputStream fileInputStream = new FileInputStream(aliOSSUtils.upload()+name);
//            ServletOutputStream outputStream = response.getOutputStream();
//            response.setContentType("image/jpeg");
//
//
//            int len=0;
//
//            byte[] bytes = new byte[1024];
//            while((len=fileInputStream.read(bytes))!=-1){
//                outputStream.write(bytes,0,len);
//                outputStream.flush();
//            }
//            outputStream.close();
//            fileInputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }





